import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Bubble,Tools,List,Button,PhotoSwipe,ActivityIndicator } from 'weaver-mobile';
import { withRouter,Route } from 'react-router-dom';
import {Form,RouteLayout } from 'weaver-mobile-page';
import AutoCheck from './AutoCheck';
import QueueAnim from 'rc-queue-anim';
const getLabel = Tools.getLabel;


@withRouter
@inject ('receptionStore')
@observer
class InvoiceInfo extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            fplx:0
        };
        // this.fplx = 0;
        this.sreenHeight = 0; 
    }

    static defaultProps = {
        prefixCls:"fna-invoiceInfo"
    }


    componentDidMount() {
        const {receptionStore,ocrInfo,location:{pathname}} = this.props;
        const {enterInvoiceByOcr,invoiceInfo} = receptionStore;
        this.sreenHeight = document.documentElement.clientHeight;

        enterInvoiceByOcr({
            operate:'invoiceShow',
            invoiceId:ocrInfo.invoiceId,
            currentRoute:pathname
        },(value)=>{
            this.setState({
                fplx:value
            })
        })

    }

    componentWillReceiveProps(nextProps){
        
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;        // 记得要返回true
    }

    componentWillUnmount(){
        const {receptionStore} = this.props;
        const {} = receptionStore;

    }


    render() {
        const { receptionStore,prefixCls,ocrInfo } = this.props;
        const { loading_page,form,showSave,showCheck,showDelete,ocrAutoCheckRoute,invoiceResult,checkJson } = receptionStore;

        let n = 0;
        if(showSave) ++n;
        if(showCheck) ++n;
        if(showDelete) ++n;

        return (
            <div className={`${prefixCls}`} >
                <ActivityIndicator
                    toast
                    text="Loading..."
                    animating={loading_page}
                />
                <div style={{height:'100%'}}>
                    <img src={ocrInfo.newImage} width="100%" style={{maxHeight:'40%'}} onClick={()=>this.imgOnClick(ocrInfo.newImage)}/>
                    <Form store={form} onChange={this.onChange} >
                        <List>
                            {showCheck ? this.getAutoCheckFields() : this.getFields()}
                        </List>
                    </Form> 
                </div>
                {(n == 2 ? <div className={'fna-invoiceInfo-footer btn_3'}>{this.getFooterBtn()}</div>
                    : ( n == 1 ? <div className={'fna-invoiceInfo-footer btn_2'}>{this.getFooterBtn()}</div>
                        :<div className={'fna-invoiceInfo-footer btn_1'}>{this.getFooterBtn()}</div>)
                    )
                }

                <Route
                    key={ocrAutoCheckRoute.id}
                    path={ocrAutoCheckRoute.path}
                    render={() => {
                        return (
                            <RouteLayout getContainer={() => document.getElementById("root")}>
                                <div
                                    key="crmListLayout"
                                    className="wm-route-layout"
                                >
                                    
                                    <AutoCheck isForm={false} invoiceResult={invoiceResult} checkJson={checkJson}/>
                                </div>
                            </RouteLayout>
                        )
                    }}
                /> 
            </div>
        )
    }

    getFooterBtn = () =>{
        const { receptionStore } = this.props;
        const { showSave,showCheck,showDelete } = receptionStore;

        let btn = [];
        btn.push(<Button type="gost"  style={{'background':'#F24D4B'}} onClick={()=>this.props.history.go(-1)}>{getLabel(26029,'上一页')}</Button>);
        {showCheck && btn.push(<Button type="primary"  onClick={this.autoCheck}>{getLabel(517364,'手动验票')}</Button>)};
        {showSave && btn.push(<Button type="primary"  onClick={this.handleCheck}>{getLabel(86,'保存')}</Button>)};
        {showDelete && btn.push(<Button type="gost"  style={{'background':'#EEB422'}} onClick={this.doDelete}>{getLabel(516582,'删除')}</Button>)};

        return btn;

    }

    //图片预览
    imgOnClick = (url)=>{
        PhotoSwipe.showImage([{url: url}], 0);
    }
    
    //重置form
    resetForm = () =>{
        const { receptionStore } = this.props;
        const { form } = receptionStore;
        const { conditioninfo } = form;

        let route = this.routeInfo.path;
        form.resetConditions(conditioninfo, route)
    }

    getFields = () => {
        const { receptionStore } = this.props;
        const { form } = receptionStore;
        // alert(JSON.stringify(toJS(form)));
        const { conditioninfo, isInit,formParams } = form;

        const groups = [];
        if (isInit) {
            conditioninfo.forEach((group) => {
                const fields = [];
                group.items.forEach((field) => {
                    fields.push(<Form.Item
                        key={field.domkey.join('__')}
                        form={form}
                        fieldConfig={field}
                        onChange={this.onChange.bind(this)}
                    />) 
                });
                
                groups.push(<div key='loading'>{fields}</div>)
            })
            
        }

        return <QueueAnim duration={900}>{groups}</QueueAnim>;
    }   
    
    onChange = (paramsObj,value) =>{
        const {receptionStore} = this.props;
        const {form} = receptionStore;
        const domkey = paramsObj.domkey[0];
        
        form.updateField(domkey,value);
    }

    //手动查验 form
    getAutoCheckFields = () =>{
        const { receptionStore } = this.props;
        const { formAuto } = receptionStore;
        // alert(JSON.stringify(toJS(form)));
        const { conditioninfo, isInit,formParams } = formAuto;

        const groups = [];
        if (isInit) {
            conditioninfo.forEach((group) => {
                const fields = [];
                group.items.forEach((field) => {
                    if(field.domkey[0] === "checkCode"){
                        if(this.state.fplx == 1 || this.state.fplx == 15 || this.state.fplx == 16){
                            fields.push(<Form.Item
                                key={field.domkey.join('__')}
                                form={formAuto}
                                fieldConfig={field}
                                onChange={this.onChangeAuto.bind(this)}
                            />) 
                        }
                        
                    }else if(field.domkey[0] === "priceWithoutTax"){
                        if(this.state.fplx == 2){
                            fields.push(<Form.Item
                                key={field.domkey.join('__')}
                                form={formAuto}
                                fieldConfig={field}
                                onChange={this.onChangeAuto.bind(this)}
                            />) 
                        }
                    }else{
                        fields.push(<Form.Item
                            key={field.domkey.join('__')}
                            form={formAuto}
                            fieldConfig={field}
                            onChange={this.onChangeAuto.bind(this)}
                        />) 
                    }
                    
                });
                
                groups.push(<div key='loading'>{fields}</div>)
            })

            
        }

        return <QueueAnim duration={900}>{groups}</QueueAnim>;
    }

    onChangeAuto = (paramsObj,value) =>{
        const {receptionStore} = this.props;
        const {formAuto} = receptionStore;
        const domkey = paramsObj.domkey[0];
        
        if(domkey == "invoiceCode"){
            if(value.length == 10 || value.length == 12){
                let invoiceType = 0;
                if(value.length == 10){
                    let eight = value.substring(7,8);
                    if("1" == eight || "2" == eight || "5" == eight || "7" == eight){
                        invoiceType = 1;
                    }else if("3" == eight || "6" == eight){
                        invoiceType = 2;
                    }
                }else if(value.length == 12){
                    let first = value.substring(0,1);
                    let eight = value.substring(7,8);
                    let elevenTwelve = value.substring(10,11) + value.substring(11,12);
                    if("0" == first){
                        if ("11" == elevenTwelve) {//增值税电子普通发票
                            invoiceType = 15;
                        } else if ("06" == elevenTwelve || "07" == elevenTwelve) {//增值税卷票
                            invoiceType = 16;
                        } else if ("04" == elevenTwelve || "05" == elevenTwelve) {//增值税普通发票
                            invoiceType = 2;
                        } else if ("12" == elevenTwelve) {//通行费发票就是增值税电子发票
                            invoiceType = 3;
                            invoiceType = 15;
                        }
                    }
                    if("1" == first && "2" == eight){//机动车销售统一发票
                        invoiceType = 4;
                    }
                    if("0" == first && "17" == elevenTwelve){//二手车销售统一发票
                        invoiceType = 5;
                    }
                }

                if(invoiceType == 1){
                    this.setState({fplx:2})
                }else if(invoiceType == 2){
                    this.setState({fplx:1})
                }else if(invoiceType == 15 || invoiceType == 16){
                    this.setState({fplx:invoiceType})
                }else if(invoiceType == 4){
                    this.setState({fplx:12})
                }else{
                    this.setState({fplx:0})

                }
            }else{
                this.setState({fplx:0})
            }
        }
     
        formAuto.updateField(domkey,value);
    }    


    //  手动验票
    autoCheck = () =>{
        const {receptionStore,ocrInfo,location:{pathname}} = this.props;
        const {formAuto,enterInvoiceByOcr} = receptionStore;
        const { formParams} = formAuto;
        
        
        if(this.state.fplx == 1 || this.state.fplx == 15 || this.state.fplx == 16){
            // formAuto.updateField('checkCode',1);
            let pass = formAuto.doValidate().pass;
            if(pass){
                this.getInvoiceParams();
            }
        }else if(this.state.fplx == 2 || this.state.fplx == 12){
            // formAuto.updateField('priceWithoutTax',1);
            let pass = formAuto.doValidate().pass;
            if(pass){
                this.getInvoiceParams();
            }
        }else{
            Bubble.error('失败')
        }


    }

    //保存
    handleCheck = () =>{
        const { receptionStore,callBackUpdata,ocrInfo } = this.props;
        const { form,enterInvoiceByOcr,invoiceType } = receptionStore;
        const { conditioninfo,formParams } = form;

        enterInvoiceByOcr({
            ...formParams,
            invoiceId:ocrInfo.invoiceId,
            operate:'saveInvoice',
            type:invoiceType
        },(value)=>{
            callBackUpdata && callBackUpdata(value);
            this.props.history.go(-1);
        })
    }

    doDelete = () =>{
        const { receptionStore,ocrInfo,callBackFn } = this.props;
        const { enterInvoiceByOcr } = receptionStore;
        enterInvoiceByOcr({
            invoiceId:ocrInfo.invoiceId,
            operate:'deleteInvoice'
        },()=>{
            callBackFn && callBackFn(ocrInfo.invoiceId)
            this.props.history.go(-1)
        })
    }

    //发票参数
    getInvoiceParams = () =>{
        const {receptionStore,ocrInfo,callBackUpdata} = this.props;
        const {enterInvoiceByOcr,formAuto,ocrAutoCheckRoute} = receptionStore;
        const { formParams} = formAuto;
        let {invoiceNumber,invoiceCode,billingDate,priceWithoutTax,checkCode} = formParams;
        billingDate = billingDate.replace("-","").replace("-","");
        let result = '';

        if(this.state.fplx == 1 || this.state.fplx == 15 || this.state.fplx == 16){
            result = "01,04,"+invoiceCode+","+invoiceNumber+",0.00,"+billingDate+","+checkCode+",0000,";
        }else if(this.state.fplx == 2 || this.state.fplx == 12){
            result = "01,01,"+invoiceCode+","+invoiceNumber+","+priceWithoutTax+","+billingDate+","+"000000,0000,";
        }

        let parms = {
            result:result,
            invoiceId:ocrInfo.invoiceId,
            operate:'authenticityCheck'
        }
        enterInvoiceByOcr(parms,(value)=>{
            // this.props.history.push(ocrAutoCheckRoute.path);
            callBackUpdata(value);
            parms = Object.assign(parms,{
                operate:'invoiceShow',
            })
            enterInvoiceByOcr(parms);

        })

        return result
    }




    

}

export default InvoiceInfo;